package com.example.myapplication.customizeView.loginpage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.myapplication.R;
import com.example.myapplication.customizeView.App;
import com.example.myapplication.customizeView.keypad.KeypadView;

import java.lang.reflect.Field;

/**
 * 点击获取验证码--==》条件是手机号码为真
 */

public class LoginPageView extends FrameLayout {
    public static final int SIZE_VERIFY_CODE_DEFAULT = 4;
    private static final String TAG = "LoginPageView";

    private int mColor;
    private int mVerifyCodeSize = SIZE_VERIFY_CODE_DEFAULT;
    private CheckBox mIsConfirm;
    private OnLoginPageActionListener mActionListener = null;
    private KeypadView mLoginKeyboard;
    private EditText mPhoneNumberInp;
    private EditText mVerifyCodeInput;
    private TextView mGetVerifyCodeBtn;
    private boolean isPhoneNumOk = false;//默认手机号码是假
    private boolean isAgreementOk = false;//默认不同意协议
    private boolean isVerifyCodeOk = false;//默认验证码为假


    public final static String REGEX_MOBIEX_ELACT = "^(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57]|19[89]|166)[0-9]{8}";
    private View mLoginBtn;

    public static final int DURATION_DEFAULT=60 * 1000;
    public static final int D_TIME_DEFAULT=1000;

    /**
     * 关注点：
     * 倒计时多长时间 duration
     * 时间间隔为多少 dt
     * 通知UI更新
     *
     */
    //duration  totalDuration MS(毫秒)
    private int mCountDownDuration =DURATION_DEFAULT ;
    private int result = mCountDownDuration;
    //dt dTime MS
    private int dTime = 1000;
    private Handler mHandler;
    private boolean isCountDowning = false;
    private CountDownTimer mCountDownTimer;
    private View mAgreementView;

    public void startCountDown(){
        mHandler = App.getHandler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                 result -= dTime;
                if(result > 0){
                    mHandler.postDelayed(this,dTime);
                    Log.d(TAG, "run:---===> "+result);
                    mGetVerifyCodeBtn.setText("("+result/1000+")秒");
                    mGetVerifyCodeBtn.setEnabled(false);
                    isCountDowning = true;
                }else{
                    result = mCountDownDuration;
                    mGetVerifyCodeBtn.setText("获取验证码");
                    mGetVerifyCodeBtn.setEnabled(true);
                    isCountDowning = false;
                    updateAllBtnState();
                }

            }
        });

    }
    private void beginCountDown(){
        mGetVerifyCodeBtn.setEnabled(false);
        isCountDowning = true;
        mCountDownTimer = new CountDownTimer(DURATION_DEFAULT, D_TIME_DEFAULT) {


            public void onTick(long millisUntilFinished) {
                //通知UI更新
                int res = (int) (millisUntilFinished / 1000);
                mGetVerifyCodeBtn.setText("(" + res + ")秒");


            }

            public void onFinish() {
//                倒計時結束

                mGetVerifyCodeBtn.setText("获取验证码");
                mGetVerifyCodeBtn.setEnabled(true);
                isCountDowning = false;
                updateAllBtnState();
                mCountDownTimer = null;

            }
        }.start();
    }

    /**
     * 验证码错误
     *
     */
    public void onVerifyCodeError(){

        //第二步，清空验证码输入框
        mVerifyCodeInput.getText().clear();
        //第三步，停止倒计时
        if (isCountDowning&&mCountDownTimer!=null){
            isCountDowning = false;
            mCountDownTimer.cancel();
            mCountDownTimer.onFinish();
        }

    }
    /**
     *登录成功
     *
     */
    public void onSuccess(){

    }

    public LoginPageView(@NonNull Context context) {
        this(context,null);
    }

    public LoginPageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoginPageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
         //初始化属性
        initAttrs(context, attrs);
//        初始化控件
        initView();

        initEvent();
//        设置有焦点时是否拉起软键盘
        disableFocus2KeyPad();
    }


    private void initEvent() {
        mAgreementView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:
            }
        });
        mIsConfirm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgreementOk = isChecked;
                updateAllBtnState();
            }
        });
        mLoginKeyboard.setOnKeyItemClickListener(new KeypadView.OnKeyItemClickListener() {
            @Override
            public void OnNumberClick(int value) {
                //数字被点击
                //插入数字
                EditText focusEdt = getFocusEdt();
                if (focusEdt != null) {
                    Editable text = focusEdt.getText();
                    int index = focusEdt.getSelectionEnd();//设置一个文本插入的起始位置为焦点末尾
                    text.insert(index,String.valueOf(value));
                }

            }

            @Override
            public void OnDeleteClick() {
                //点击退格键
                EditText focusEdt = getFocusEdt();
                if (focusEdt != null) {
                    Editable editable = focusEdt.getText();
                    int index = focusEdt.getSelectionEnd();
                    if (index>0){
                        editable.delete(index-1,index);
                    }
                }

            }
        });
//        mLoginKeyboard.setOnKeyPressListener(new LoginKeyboard.OnKeyPressListener() {
//            @Override
//            public void OnNumberPress(int number) {
//                //数字被点击
//                //插入数字
//                EditText focusEdt = getFocusEdt();
//                if (focusEdt != null) {
//                    Editable text = focusEdt.getText();
//                    int index = focusEdt.getSelectionEnd();//设置一个文本插入的起始位置为焦点末尾
//                    text.insert(index,String.valueOf(number));
//                }
//            }
//
//            @Override
//            public void OnBackPress() {
//                //点击退格键
//                EditText focusEdt = getFocusEdt();
//                if (focusEdt != null) {
//                    Editable editable = focusEdt.getText();
//                    int index = focusEdt.getSelectionEnd();
//                    if (index>0){
//                        editable.delete(index-1,index);
//                    }
//                }
//
//
//            }
//        });
        mGetVerifyCodeBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //todo: get verify code
                if (mActionListener != null) {
                    //拿到手机号
                    String phoneNumber = mPhoneNumberInp.toString().trim();
                    mActionListener.onGetVerifyCodeClick(phoneNumber);
                    //开启倒计时

                    //startCountDown();
                    beginCountDown();
                }else {
                    throw new IllegalArgumentException("NO ACTION TO START");
                }
            }
        });
        mVerifyCodeInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isVerifyCodeOk = s.length()==4;
                updateAllBtnState();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPhoneNumberInp.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //变化的时候去检测手机号码是否符合格式
                //TODO:
                String phoneNum = s.toString();
                boolean isMatch = phoneNum.matches(REGEX_MOBIEX_ELACT);
                isPhoneNumOk = phoneNum.length()==11 && isMatch;

                    updateAllBtnState();



            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mLoginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mActionListener != null){
                    mActionListener.onConfirmClick(getVerifyCode(),getPhoneNum());
                }
            }
        });
    }
    private String getPhoneNum(){
        return mPhoneNumberInp.toString().trim();
    }
    private String getVerifyCode(){
        return mVerifyCodeInput.toString().trim();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.login_page_view,this);
        mIsConfirm = this.findViewById(R.id.report_check_box);
        mVerifyCodeInput = this.findViewById(R.id.verify_code_input_box);
        if (mColor != -1){
            mIsConfirm.setTextColor(mColor);
        }

        mVerifyCodeInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mVerifyCodeSize)});
        mLoginKeyboard = this.findViewById(R.id.number_key_pad);
        mPhoneNumberInp = this.findViewById(R.id.phone_number_input_box);
        mPhoneNumberInp.requestFocus();
        mGetVerifyCodeBtn = this.findViewById(R.id.get_verify_code_btn);
        mLoginBtn = this.findViewById(R.id.loginBtn);
        mAgreementView = this.findViewById(R.id.agreement_text_tips);
        updateAllBtnState();
        disableCopyAndPaste(mPhoneNumberInp);
        disableCopyAndPaste(mVerifyCodeInput);


    }

    private void initAttrs(@NonNull Context context, @Nullable AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoginPageView);
        mColor = a.getColor(R.styleable.LoginPageView_mainColor, -1);
        mVerifyCodeSize = a.getInt(R.styleable.LoginPageView_verifyCodeSize, SIZE_VERIFY_CODE_DEFAULT);
        mCountDownDuration = a.getInt(R.styleable.LoginPageView_countDownDuration, DURATION_DEFAULT);

        //
        a.recycle();
    }

    public int getColor() {
        return mColor;
    }

    public void setColor(int mColor) {
        this.mColor = mColor;
    }

    public int getCountDownDuration() {
        return mCountDownDuration;
    }

    public void setCountDownDuration(int mCountDownDuration) {
        this.mCountDownDuration = mCountDownDuration;
    }

    public int getVerifyCodeSize() {
        return mVerifyCodeSize;
    }

    public void setVerifyCodeSize(int mVerifyCodeSize) {
        this.mVerifyCodeSize = mVerifyCodeSize;
    }
    private void updateAllBtnState(){
        if (! isCountDowning){
            mGetVerifyCodeBtn.setEnabled(isPhoneNumOk);

        }
        mLoginBtn.setEnabled(isPhoneNumOk&&isAgreementOk&&isVerifyCodeOk);
        mAgreementView.setEnabled(isAgreementOk);

    }

    /**
     * 获取当前有焦点的输入框
     *
     * 要注意判空
     * @return null or edittext instanceof
     */
    private EditText getFocusEdt(){
        View view = this.findFocus();
        if (view instanceof EditText){
            return (EditText)view;
        }
        return null;
    }

    public void setOnLoginPageActionListener(OnLoginPageActionListener listener){
        this.mActionListener = listener;

    }

    public interface OnLoginPageActionListener{
        void onGetVerifyCodeClick(String phoneNum);
        void onOpenAgreementClick();
        void onConfirmClick(String verifyCode,String phoneNum);

    }

    private void disableFocus2KeyPad() {
        mPhoneNumberInp.setShowSoftInputOnFocus(false);//
        mVerifyCodeInput.setShowSoftInputOnFocus(false);
    }

    @SuppressLint("ClickableViewAccessibility")
    public void disableCopyAndPaste(final EditText editText) {
        try {
            if (editText == null) {
                return ;
            }

            editText.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });
            editText.setLongClickable(false);
            editText.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        // setInsertionDisabled when user touches the view
                        setInsertionDisabled(editText);
                    }

                    return false;
                }
            });
            editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setInsertionDisabled(EditText editText) {
        try {
            Field editorField = TextView.class.getDeclaredField("mEditor");
            editorField.setAccessible(true);
            Object editorObject = editorField.get(editText);

            // if this view supports insertion handles
            Class editorClass = Class.forName("android.widget.Editor");
            Field mInsertionControllerEnabledField = editorClass.getDeclaredField("mInsertionControllerEnabled");
            mInsertionControllerEnabledField.setAccessible(true);
            mInsertionControllerEnabledField.set(editorObject, false);

            // if this view supports selection handles
            Field mSelectionControllerEnabledField = editorClass.getDeclaredField("mSelectionControllerEnabled");
            mSelectionControllerEnabledField.setAccessible(true);
            mSelectionControllerEnabledField.set(editorObject, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
